const cluster = require('node:cluster');
const http = require('node:http');

// 返回对程序应该使用的默认并行度量的估计值。总是返回一个大于零的值。
const numCPUs = require("node:os").availableParallelism();
const process = require('node:process');

let server 

if (cluster.isPrimary) {
    console.log(`Primary ${process.pid} is running`);

    // Fork workers.
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} died`);
    });


    
} else {
    // Workers can share any TCP connection
    // In this case it is an HTTP server
    server = http.createServer((req, res) => {
        res.writeHead(200);
        res.end('hello world\n');
    }).listen(8000);

    console.log(cluster.worker);

    console.log(`Worker ${process.pid} started , its parent pid is ${process.ppid} `);
}
